import { ref, reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { get, update, del, cover } from '@/api/store/goods'
import menuStore from './menu'

// 初始化
const goodsStore = store()

// 分页
goodsStore.page = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: [10, 20, 50, 100],
  loading: false
})

// 查询类型
goodsStore.where = reactive({ 
  key: 'number', 
  value: ''
})

// 生成查询数据
goodsStore.getWhere = () => {
  // 查询方式
  const where = { [goodsStore.where.key]: goodsStore.where.value }
  // 合并分类
  where.menu_id = menuStore.getIndex()
  // 合并数据
  return Object.assign(where, goodsStore.getData())
}

goodsStore.data = ref({
  supplier_id: 0
})

// 选中商品
goodsStore.index = ref({})
goodsStore.setIndex = row => {
  goodsStore.index.value = Object.assign({}, row)
}
goodsStore.getIndex = () => {
  return goodsStore.index.value
}

goodsStore.get = () => {
  return new Promise((resolve, jeject) => {
    goodsStore.page.loading = true
    get(goodsStore.getWhere()).then(res => {
      goodsStore.setList(res.data)
      // 分页
      goodsStore.page.current = res.current_page
      goodsStore.page.pageSize = res.per_page
      goodsStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      goodsStore.page.loading = false
    })
  })
}

goodsStore.update = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

goodsStore.del = (...arge) => {
  return new Promise((resolve, jeject) => {
    del(...arge).then(res => {
      goodsStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 重置请求
goodsStore.reset = (page, size) => {
  goodsStore.page.current = page
  goodsStore.page.pageSize = size
  goodsStore.getData().page = page
  goodsStore.getData().page_size = size

  // 开始加载
  goodsStore.get()
}

goodsStore.cover = (...arge) => {
  return new Promise((resolve, jeject) => {
    cover(...arge).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default goodsStore